package com.may.wind.service;

import com.may.wind.dao.RoleRepository;
import com.may.wind.dao.UserRepository;
import com.may.wind.entity.Menu;
import com.may.wind.entity.Permission;
import com.may.wind.entity.Role;
import com.may.wind.entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class RoleService {
    @Autowired
    RoleRepository roleRepository;
    @Autowired
    UserRepository userRepository;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    PermissionService permissionService;
    @Autowired
    RolePermissionService rolePermissionService;
    @Autowired
    MenuService menuService;

    public List<Role> getAllByPermissionsAndMenus() {
        List<Role> roles = roleRepository.findAll();
        Set<Permission> permissions;
        List<Menu> menus;
        for (Role role : roles) {
            permissions = permissionService.getPermissionsByRoleId(role.getId());
            menus = menuService.getMenusByRoleId(role.getId());
            role.setPermissions(permissions);
            role.setMenus(menus);
        }
        return roles;
    }

    public List<Role> findAll() {
        return roleRepository.findAll();
    }


    public void addOrUpdate(Role role) {
        roleRepository.save(role);
    }

    public List<Role> getAllByUser(String username) {
        long userId = userRepository.findByUsername(username).getId();
        List<Long> roleIds = userRoleService.getAllByUserId(userId).stream().map(UserRole::getRolesId).collect(Collectors.toList());
        return roleRepository.findAllById(roleIds);
    }

    public Role updateRoleStatus(Role role) {
        Role roleInDB = roleRepository.findById(role.getId());
        roleInDB.setEnabled(role.getEnabled());
        return roleRepository.save(roleInDB);
    }

    public void editRole(@RequestBody Role role) {
        roleRepository.save(role);
        rolePermissionService.savePermissionsChanges(role.getId(), role.getPermissions());
    }
}
